﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using WeifenLuo.WinFormsUI.Docking;
using docmgr.BLL;

namespace docmgr.WinForm {

    /// <summary>
    /// 
    /// </summary>
    public partial class UserList : DockContent
    {

        #region 预置基本参数开始
        //权限项名称
        private string PowerItemName = "User";
        //当前操作员       
        string OpManage = "YCSK";//Common.curUser.UserCode;

        //--表格结构
        private const string TableName = "User";
        //--表格主键
        string ID;
                // 表的字段结构
        string[] tbfelids = new string[]{
		"ID,int,ID",
		"Username,varchar,用户名",
		"Password,varchar,密码",
		"DepartmentID,int,部门id",
		"PositionID,int,岗位id",
		"Remark,varchar,备注",
		"Name,varchar,姓名"};


        //-- 声明业务对象
        docmgr.BLL.User bll;
    
        //-- 创建数据源
        DataSet mainDs = new DataSet();
        DataTable mainDt = new DataTable();
       
        //查询条件
        string hidSQL = ""; 
        StringBuilder constsql = new StringBuilder();

        //窗体初始化结束标志
        bool IsWinInitOver = false;
        #endregion

        #region 构造函数 、Load()、Shown()事件
        public UserList() {
            InitializeComponent();
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Pixel, ((byte)(134)));

            initWindow();
        }

        private void UserList_Load(object sender,EventArgs e) {
            //--重新绑定表格数据源
            //BindGrid(null);
            BindDataWithPage(1);
            
        }
        private void UserList_Shown(object sender,EventArgs e) {
            //窗体初始化结束标志
            IsWinInitOver = true;
        }
        #endregion

        #region 自定义初始化窗体 initWindow

        public void initWindow() {
            //--插入选择日期范围的日期控件
            /*DateTimePicker dateBegin = new DateTimePicker();
            DateTimePicker dateEnd = new DateTimePicker();
            dateBegin.Width = dateEnd.Width = 110;           
            toolStrip1.Items.Insert(5, new ToolStripControlHost(dateBegin, "dateBegin"));
            toolStrip1.Items.Insert(7, new ToolStripControlHost(dateEnd, "dateEnd"));*/
           
             //创建业务对象
             bll = new docmgr.BLL.User(); 
        }

        //设置窗体快捷键
        private void form_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e) {
            if (!e.Control)
                return;
            switch (e.KeyCode) {
                case Keys.N://新建
                    this.tsbtnNew_Click(this.tsbtnNew, null);
                    break;
                case Keys.S://搜索
                    //this.tsbtnSave_Click(this.tsbtnSave, null);
                    break;
                case Keys.D://删除
                    this.tsbtnDel_Click(this.tsbtnDel, null);
                    break;
		case Keys.W://关闭窗口
                    this.tsbtnClose_Click(this.tsbtnDel, null);
                    break;
                case Keys.H://显示帮助
                    this.tsbtnHelp_Click(this.tsbtnHelp, null);
                    break;
            }
        }
        #endregion       

        #region -- 主工具栏操作 新建、保存、删除、显示帮助
        //打开新建窗口
        private void tsbtnNew_Click(object sender, EventArgs e) {
            //if (!Common.getUserAccess(this.PowerItemName, opType.bDelete)) {
            //    MessageBox.Show(this, "没有操作权限", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            //    return;
            //}
            using (docmgr.WinForm.UserOperation frm = new docmgr.WinForm.UserOperation())
            {
                frm.WindowState = FormWindowState.Normal;
                frm.StartPosition = FormStartPosition.CenterScreen;
                if(frm.ShowDialog() == DialogResult.OK) {
                    //BindGrid(null);
                    
                }
                BindDataWithPage(1);
            }
        }
        //保存列表
        protected void tsbtnSave_Click(object sender, EventArgs e) {
            //if (!Common.getUserAccess(this.PowerItemName, opType.bEdit)) {
            //    MessageBox.Show(this, "没有操作权限", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            //    return;
            //}          
            //业务处理       
            SaveGrid();
        }

        //删除当前行记录
        private void tsbtnDel_Click(object sender, EventArgs e) {
            //if (!Common.getUserAccess(this.PowerItemName, opType.bDelete)) {
            //    MessageBox.Show(this, "没有操作权限", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            //    return;
            //}
            if (this.dataGridView1.CurrentRow == null)
                return;
            string key = this.dataGridView1.CurrentRow.Cells["ColumnID"].Value.ToString();
            if (DialogResult.OK == MessageBox.Show(this, "确定要删除该条记录？", "系统提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Information))
            {
                try
                {
                    bll.DeleteByKey(key);
                }
                catch (Exception ex1)
                {
                    MessageBox.Show("无法删除该记录");
                }
                finally
                //BindGrid(null);
                {
                    BindDataWithPage(allenPage1.PageIndex);
                }
            }
        }
        //搜索查询
        private void tsBtnSearch_Click(object sender, EventArgs e)
        {
            string condition = "";//在这里设置查询条件,如 "title like '%good%'",为空就是查询所有记录
            //BindGrid(condition);//重新绑定表格

            if (tsTBoxKey.Text!="")
            {
                condition += String.Format(" u.Name like '%{0}%' or  u.Username like '%{0}%' or  d.Name like '%{0}%' or  p.Name like '%{0}%' or  u.Remark like '%{0}%' ", tsTBoxKey.Text.Trim());
            }

            hidSQL = condition;
            BindDataWithPage(1);
        }
        //关闭窗口
        private void tsbtnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        //显示帮助
        private void tsbtnHelp_Click(object sender, EventArgs e) {

        }
        #endregion

        #region -- 主要业务  dataGridView表格相关操作
        /// <summary>
        /// 根据查询条件绑定表格数据源
        /// </summary>
        /// <param name="condition">查询条件,为null或者空就是查询所有记录</param>
        private void BindGrid(string condition)
        {
            mainDt = bll.GetList(condition);//查询
            this.bindingSource1.DataSource = mainDt;
            this.dataGridView1.DataSource = this.bindingSource1;
            //加载表格样式
            Common.LoadGridStyleByXML(this.Name, dataGridView1);
        }
        /// <summary>
        /// 更新数据源数据
        /// </summary>
        private void SaveGrid()
        {                     
            StringBuilder opmsg = new StringBuilder();
            int result = bll.Update(mainDt);
            if (result > 0)
            {
                opmsg.AppendLine("保存成功");
            } else {
                opmsg.AppendLine("保存失败");
            }
            //弹出反馈消息
             MessageBox.Show(this, opmsg.ToString(), "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
        private void dataGridView1_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {            
                DataGridView.HitTestInfo info = dataGridView1.HitTest(e.Location.X, e.Location.Y);
                if (info.ColumnIndex > -1)
                {
                    if (info.RowIndex > -1)
                        dataGridView1.CurrentCell = dataGridView1.Rows[info.RowIndex].Cells[info.ColumnIndex];
                    Point point = this.PointToClient(new Point(e.X, e.Y));
                    Common.showContextMenu(dataGridView1, point, this.Name, false, false);
                }
            }
        }
        private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex > -1 && e.RowIndex > -1)
            {
                string key = dataGridView1.Rows[e.RowIndex].Cells["ColumnID"].Value.ToString();

                using (docmgr.WinForm.UserOperation frm = new docmgr.WinForm.UserOperation(key))
                {
                    frm.WindowState = FormWindowState.Normal;
                    frm.StartPosition = FormStartPosition.CenterScreen;
                    if (frm.ShowDialog() == DialogResult.OK)
                    {
                        //BindGrid(null);
                       
                    }
                    BindDataWithPage(1);
                }
            }
        }
        private void dataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {
            for (int i = 0; i < dataGridView1.Rows.Count; i++)
            {
                dataGridView1.Rows[i].HeaderCell.Value = (i + 1).ToString();
            }
        }
        #endregion

        private void allenPage1_PageIndexChanged(object sender, EventArgs e)
        {
            BindDataWithPage(allenPage1.PageIndex);
        }

        private void BindDataWithPage(int Index)
        {
            allenPage1.PageIndex = Index;
            String fields = " u.ID,u.name Name,u.Username Username,d.Name DepartmentID,p.Name PositionID,u.Remark ";
            DataSet ds = bll.GetPage(fields, hidSQL, allenPage1.PageIndex, allenPage1.PageSize);

            dataGridView1.DataSource = ds.Tables[0];

            //获取并设置总记录数
            allenPage1.RecordCount = Convert.ToInt32(ds.Tables[1].Rows[0][0]);
            allenPage1.Refresh();
        }
    }
}